/**
 * Markets
 *
 * for MarketsController
 */
var Markets = {};

/**
 * functions to execute when document is ready
 *
 * only for MarketsController
 *
 * @return void
 */
Markets.documentReady = function() {
    Markets.addBank();
    Markets.removeBank();
    Markets.sortDD('all');
}

/**
 * add meta field
 *
 * @return void
 */
Markets.addBank = function() {
    $('a.addBankField').click(function() {
        var t_bank = $(this).attr('rel');
        var id = $('select#Bank'+t_bank+'Bank'+t_bank+' option:selected').val();
        $.get(Croogo.basePath+'admin/markets/add_bank'+t_bank+'/'+id, function(data) {
            $('#bankField'+t_bank).before(data);
            $('a.removeBankField').unbind();
            Markets.removeBank();
            $("select#Bank"+t_bank+"Bank"+t_bank+" option[value='"+id+"']").remove();
        });
        return false;
    });
}

/**
 * remove meta field
 *
 * @return void
 */
Markets.removeBank = function() {
    $('a.removeBankField').click(function() {
        var that = $(this);
        if (that.attr('rel') != '') {
            $.getJSON(Croogo.basePath+'admin/markets/delete_bank/'+that.attr('rel'), function(data) {
                if (data.success) {
                    var id = that.attr('title');
                    var value = $('#Bank'+id+'Id').val();
                    var text = $('#Bank'+id+'Name').val();
                    var t_bank = $('#Bank'+id+'TBank').val();
                    $('select#Bank'+t_bank+'Bank'+t_bank).append('<option value="'+value+'">'+text+'</option>');
                    Markets.sortDD('Bank'+t_bank+'Bank'+t_bank);
                    that.parents().parents().parents('.tbl-contact2').remove();
                } else {
                    // error
                }
            });
        } else {
            that.parents().parents().parents('.tbl-contact2').remove();
        }
        return false;
    });
}

Markets.sortDD = function(id) {
    if(id=='all') {
        id = 'select';
    } else {
        id = '#'+id;
    }
    // Loop for each select element on the page.
    $(id).each(function() {

        // Keep track of the selected option.
        var selectedValue = $(this).val();

        // Sort all the options by text. I could easily sort these by val.
        $(this).html($("option", $(this)).sort(function(a, b) {
        return a.text == b.text ? 0 : a.text < b.text ? -1 : 1
        }));

        // Select one option.
        $(this).val(selectedValue);
    });
}

/**
 * document ready
 *
 * @return void
 */
$(document).ready(function() {
    if (Croogo.params.controller == 'markets') {
        Markets.documentReady();
    }
});
